<template>
  <div class="modal" v-show="$store.state.isOpenLogin">
    <div class="modal_bg" @click="closeLogin"></div>
    <div class="modal_content">
      <img class="close" @click="closeLogin" src="../assets/images/login/userArrow.png" alt />
      <section>
        <span :class="{ active: showPhone }" @click="showPhone = true">手机号登录</span>
        <span :class="{ active: !showPhone }" @click="wechatLoginFn">微信扫码登录</span>
      </section>
      <div class="phoneLogin" v-show="showPhone">
        <div class="tanxin line">
          <input type="text" placeholder="请输入手机号" v-model="phone" />
        </div>
        <!-- 滑块验证码 -->
        <div class="verify_box">
          <slide-verify
            :l="42"
            :r="10"
            :w="360"
            :h="155"
            slider-text="向右滑动"
            @success="onSuccess"
            @fail="onFail"
            @refresh="onRefresh"
          ></slide-verify>
          <div>{{ msg }}</div>
        </div>
        <div class="tanxin line">
          <input type="text" placeholder="请输入验证码" v-model="code" />
          <div class="btn" @click="getCodeFn" v-if="codeStatus">获取验证码</div>
          <div class="daojishi" v-else>{{ count }}</div>
        </div>

        <div class="btn_login" @click="submitFn">登陆</div>
      </div>
      <div id="weixin" v-show="!showPhone"></div>
    </div>
  </div>
</template>

<script>
import { SendPhone, LoginApi, bindWechatPhoneApi } from "@/request/api";
const validatephone = phone => {
  let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
  // 手机号正确 返回true  错误 返回false
  return reg.test(phone.trim());
};
export default {
  data() {
    return {
      // 控制是微信扫码 还是 手机号
      showPhone: false,
      // 手机号
      phone: "15388280226",
      // 验证码
      code: "6627",
      // 滑块提示
      msg: "向右滑动",
      // 倒计时
      count: 5,
      // 获取验证码的状态，true 代表要显示 "获取验证码",false代表显示倒计时
      codeStatus: true
    };
  },
  methods: {
    // 切换到微信登录
    wechatLoginFn() {
      this.showPhone = false;
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa(process.env.VUE_APP_STATE_URL + _this.$route.path)
        ),
        // 调用样式文件
        href:
          "data:text/css;base64,Lyogd3hsb2dpbi5jc3MgKi8NCi5pbXBvd2VyQm94IC50aXRsZSwgLmltcG93ZXJCb3ggLmluZm97DQogICAgZGlzcGxheTogbm9uZTsNCn0NCg0KLmltcG93ZXJCb3ggLnFyY29kZXsNCiAgICBtYXJnaW4tdG9wOiAyMHB4Ow0KfQ0KIA=="
      });
    },
    closeLogin() {
      // 关闭模态框
      this.$store.commit("changeIsLogin", false);
    },
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "登陆成功, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.msg = "验证失败";
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    // 点击登录按钮
    submitFn() {
      // 验证手机号格式是否正确
      let result = validatephone(this.phone);
      if (!result) {
        // 检验手机号错误的时候
        this.$store.dispatch("AsyncToast", {
          content: "手机号错误",
          icon: "danger"
        });
        return;
      }
      // 校验验证码是否填写
      let mycode = this.code.trim();
      if (mycode == "") {
        this.$store.dispatch("AsyncToast", {
          content: "请输入验证码",
          icon: "danger"
        });
        return;
      }
      // 校验滑块是否滑动
      if (
        this.msg == "再试一次" ||
        this.msg == "验证失败" ||
        this.msg == "向右滑动"
      ) {
        this.$store.dispatch("AsyncToast", {
          content: "请完成拼图",
          icon: "danger"
        });
        return;
      }

      // 存在uuid
      let uuid = sessionStorage.getItem("uuid");
      if (uuid) {
        // 如果存在 uuid 的东西 ，证明就是微信扫码登录得到的
        bindWechatPhoneApi({
          phone: this.phone,
          verifyCode: this.code,
          uuid: uuid
        }).then(res => {
          if (res.data.code === 0) {
            // 已经登录成功
            // 存储token
            localStorage.setItem("x-auth-token", res.data["x-auth-token"]);
            // 提示登录成功
            let toastObj = {
              content: res.data.message,
              icon: "success"
            };
            this.$store.dispatch("AsyncToast", toastObj);
            // 关闭登录框
            this.$store.commit("changeIsLogin", false);
            // 更新header组件
            this.$emit("updateKeyFn");
            // 删除地址栏的code
            this.$router.push(this.$route.path);
            // 删除uuid
            sessionStorage.removeItem("uuid");
          }
        });
      } else {
        LoginApi({
          verifyCode: this.code,
          phone: this.phone
        }).then(res => {
          // console.log(res);
          if (res.data.code === 0) {
            // 存储token
            localStorage.setItem("x-auth-token", res.data["x-auth-token"]);
            // 提示登录成功
            let toastObj = {
              content: res.data.message,
              icon: "success"
            };
            this.$store.dispatch("AsyncToast", toastObj);
            // 关闭登录框
            this.$store.commit("changeIsLogin", false);
            // 更新header组件
            this.$emit("updateKeyFn");
            // 删除地址栏的code
            this.$router.push(this.$route.path);
            // 删除uuid
            sessionStorage.removeItem("uuid");
          }
        });
      }
    },
    // 获取验证码
    getCodeFn() {
      // 判断有没有手机号
      let result = validatephone(this.phone);
      if (!result) {
        // 检验手机号错误的时候
        this.$store.dispatch("AsyncToast", {
          content: "请重新输入手机号",
          icon: "danger"
        });

        return;
      }
      // 如果手机号没问题， 就继续正常往下走
      // 获取验证码 -->  倒计时功能
      SendPhone({
        phone: this.phone
      }).then(res => {
        if (res.data.code === 0) {
          // 成功发送验证码
          let obj = { content: res.data.message, icon: "success" };
          this.$store.dispatch("AsyncToast", obj);
          this.codeStatus = false; // 显示倒计时
          let timer = setInterval(() => {
            this.count--;
            if (this.count === 0) {
              // 终止定时器
              clearInterval(timer);
              this.count = 5; // 初始化数字
              // 显示 "获取验证码" 按钮
              this.codeStatus = true;
            }
          }, 1000);
        } else {
          // 发送验证码失败
          let obj = { content: res.data.message, icon: "info" };
          this.$store.dispatch("AsyncToast", obj);
        }
      });
    }
  }
};
</script>
 
<style lang = "less" scoped>
@import "../assets/base.less";

.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .modal_bg {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.4);
  }
  .modal_content {
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url(../assets/images/login/loginBg.png) no-repeat;
    .close {
      position: absolute;
      top: 20px;
      right: 60px;
    }
    section {
      display: flex;
      justify-content: center;
      padding-top: 50px;
      margin-bottom: 30px;
      span {
        color: #ccc;
        cursor: pointer;
        &:nth-of-type(1) {
          border-right: 1px solid #ccc;
          padding-right: 10px;
          margin-right: 10px;
        }
        &.active {
          color: #333;
        }
      }
    }
    .line {
      width: 360px;
      margin: 0 auto 20px;
      height: 50px;
      input {
        flex: 1;
        text-indent: 1em;
        outline: none;
      }
      .btn {
        width: 90px;
        height: 50px;
        text-align: center;
        background: @blue;
        color: #fff;
        cursor: pointer;
        line-height: 50px;
        margin-left: 10px;
      }
      .daojishi {
        color: @black;
        background-color: #ccc;
        text-align: center;
        width: 90px;
        height: 50px;
        cursor: pointer;
        margin-left: 10px;
        line-height: 50px;
      }
    }
    .btn_login {
      width: 360px;
      height: 50px;
      text-align: center;
      background: @blue;
      color: #fff;
      cursor: pointer;
      line-height: 50px;
      margin: auto;
    }
  }
}
.verify_box {
  width: 360px;
  margin: 0 auto 20px;
  /deep/.slide-verify {
    width: 358px !important;
    canvas {
      position: absolute;
      top: -150px;
      left: 0;
      display: none;
      box-sizing: border-box;
    }
    &:hover {
      canvas {
        display: block;
      }
    }
  }
}

#weixin {
  width: 300px;
  margin: 0 auto;
  .title {
    display: none;
  }
}
</style>